<template>
  <view class="container">
    <!-- 顶部搜索区域 -->
    <view class="header">
      <view class="search-box">
        <view class="search-input">
          <text class="search-icon">🔍</text>
          <input type="text" placeholder="搜索标签" confirm-type="search" @confirm="onSearch" />
        </view>
      </view>
    </view>
    
    <!-- 分类列表 -->
    <scroll-view scroll-x class="category-scroll" :show-scrollbar="false">
      <view class="category-list">
        <view 
          v-for="item in sortedCategories" 
          :key="item.id"
          class="category-item"
          :class="{'category-item-active': currentCategory && currentCategory.id === item.id}"
          @tap="switchCategory(item)"
        >
          {{item.categoryTitle}}
        </view>
      </view>
    </scroll-view>
    
    <!-- 文章列表 -->
    <scroll-view 
      scroll-y 
      class="content-scroll"
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      @refresherrefresh="onRefresh"
      :refresher-triggered="isRefreshing"
    >
      <view class="article-list">
        <view 
          v-for="item in articles" 
          :key="item.id"
          class="article-item"
          @tap="goDetail(item)"
        >
          <image 
            :src="getFirstImage(item.contentImg)" 
            mode="aspectFill"
            class="article-image"
            @error="onImageError"
          />
          <view class="article-info">
            <text class="article-title">{{item.contentTitle}}</text>
            <view v-if="item.contentTags" class="article-tags">
              <text v-for="tag in getTagArray(item.contentTags)" :key="tag" class="tag">{{tag}}</text>
            </view>
            <text class="article-desc">{{item.contentDescription || '暂无描述'}}</text>
            <view class="article-meta">
              <text class="meta-item">{{item.contentDatetime}}</text>
              <text class="meta-item">浏览 {{item.contentHit || 0}}</text>
              <text v-if="item.contentAuthor" class="meta-item">{{item.contentAuthor}}</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view v-if="loading" class="loading">
        <text class="loading-text">加载中...</text>
      </view>
      <view v-if="!hasMore && articles.length > 0" class="no-more">
        <text class="no-more-text">没有更多数据了</text>
      </view>
      
      <!-- 空状态 -->
      <view v-if="!loading && articles.length === 0" class="empty-state">
        <text class="empty-text">暂无内容</text>
      </view>
    </scroll-view>
    
    <!-- 错误状态 -->
    <view v-if="error" class="error-container">
      <text class="error-text">{{error}}</text>
      <button @tap="retry" class="retry-btn">重试</button>
    </view>
    
    <!-- 快速分享组件 - 分享当前分类 -->
    <quick-share 
      v-if="currentCategory && !loading && !error"
      type="category"
      :targetId="currentCategory.id"
      :title="currentCategory.categoryTitle || '精选内容'"
      :description="currentCategory.description || '分享精选内容'"
      :image="''"
    />
  </view>
</template>

<script>
import { categoryApi, articleApi } from '@/api/config';
import config from '@/config';
import QuickShare from '@/components/QuickShare.vue';

export default {
  components: {
    QuickShare
  },
  data() {
    return {
      categories: [],
      articles: [],
      currentCategory: null,
      page: 1,
      size: 10,
      loading: false,
      hasMore: true,
      isRefreshing: false,
      searchText: '',
      error: '',
      isLoggedIn: false
    }
  },
  computed: {
    sortedCategories() {
      // 按 categorySort 字段排序，只显示叶子节点（leaf: true）
      // 值越大越靠前
      return this.categories
        .filter(item => item.leaf === true)
        .sort((a, b) => {
          const sortA = parseInt(a.categorySort) || 0;
          const sortB = parseInt(b.categorySort) || 0;
          return sortB - sortA; // 降序排列
        });
    }
  },
  onLoad() {
    this.checkLoginStatus();
  },
  onShow() {
    // 页面显示时刷新数据，确保内容最新
    this.refreshData();
  },
  // 分享给好友（小程序专用）
  onShareAppMessage() {
    if (!this.currentCategory) return {};
    
    return {
      title: this.currentCategory.categoryTitle || '精选内容',
      path: `/pages/index/index?categoryId=${this.currentCategory.id}`,
      imageUrl: ''
    };
  },
  // 分享到朋友圈（小程序专用）
  onShareTimeline() {
    if (!this.currentCategory) return {};
    
    return {
      title: this.currentCategory.categoryTitle || '精选内容',
      query: `categoryId=${this.currentCategory.id}`,
      imageUrl: ''
    };
  },
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      try {
        const userInfoStr = uni.getStorageSync('userInfo');
        if (!userInfoStr) {
          console.log('未找到用户信息，需要登录');
          this.redirectToLogin();
          return;
        }
        
        const userInfo = JSON.parse(userInfoStr);
        const loginTime = userInfo.loginTime || 0;
        const currentTime = new Date().getTime();
        
        // 检查登录是否过期（24小时）
        if (currentTime - loginTime > 24 * 60 * 60 * 1000) {
          console.log('登录已过期，需要重新登录');
          this.redirectToLogin();
          return;
        }
        
        this.isLoggedIn = true;
        this.loadPageData();
      } catch (error) {
        console.error('检查登录状态失败:', error);
        this.redirectToLogin();
      }
    },
    
    // 重定向到登录页
    redirectToLogin() {
      uni.redirectTo({
        url: '/pages/login/login',
        fail: (err) => {
          console.error('跳转到登录页失败:', err);
          uni.navigateTo({
            url: '/pages/login/login'
          });
        }
      });
    },
    
    async loadPageData() {
      try {
        this.loading = true;
        this.error = '';
        
        // 1. 获取分类数据
        console.log('[首页] 开始加载分类数据');
        const categoryRes = await categoryApi.getList();
        
        if (typeof categoryRes === 'string' && categoryRes.includes('<html>')) {
          console.error('服务器返回了HTML内容，可能需要登录');
          this.redirectToLogin();
          return;
        }
        
        if (categoryRes.code === 200) {
          this.categories = categoryRes.data.rows || [];
          console.log('[首页] 分类数据加载成功:', this.categories);
          
          // 默认选择第一个分类
          if (this.sortedCategories.length > 0) {
            this.currentCategory = this.sortedCategories[0];
          }
        }
        
        // 2. 获取文章数据
        await this.loadArticles();
        
      } catch (error) {
        console.error('[首页] 加载失败:', error);
        this.error = error.message || '页面加载失败';
        
        // 检查是否是登录相关错误
        if (error.message && (
          error.message.includes('登录') || 
          error.message.includes('session') || 
          error.message.includes('授权')
        )) {
          this.redirectToLogin();
        }
      } finally {
        this.loading = false;
      }
    },
    
    async loadArticles(isLoadMore = false) {
      if (this.loading && !isLoadMore) return;
      
      try {
        if (!isLoadMore) {
          this.loading = true;
        }
        
        const params = {
          categoryId: this.currentCategory?.id,
          pageNo: this.page,
          size: this.size,
          keyword: this.searchText
        };
        
        console.log('[首页] 加载文章:', params);
        const res = await articleApi.getList(params);
        
        // 检查是否返回了HTML内容
        if (typeof res === 'string' && res.includes('<html>')) {
          console.error('服务器返回了HTML内容，可能需要登录');
          this.redirectToLogin();
          return;
        }
        
        if (res.code === 200) {
          const list = res.data.rows || [];
          console.log('[首页] 文章加载成功:', list);
          this.articles = isLoadMore ? [...this.articles, ...list] : list;
          this.hasMore = list.length === this.size;
        }
      } catch (error) {
        console.error('[首页] 文章加载失败:', error);
        if (!isLoadMore) {
          this.error = error.message || '文章加载失败';
          
          // 如果是登录错误，跳转到登录页
          if (error.message && error.message.includes('登录')) {
            this.redirectToLogin();
          }
        }
      } finally {
        this.loading = false;
        if (this.isRefreshing) {
          this.isRefreshing = false;
        }
      }
    },
    
    async switchCategory(category) {
      try {
        console.log('[首页] 切换分类:', category);
        this.currentCategory = category;
        this.page = 1;
        this.hasMore = true;
        this.articles = [];
        await this.loadArticles();
      } catch (error) {
        console.error('[首页] 切换分类失败:', error);
        uni.showToast({
          title: '切换分类失败',
          icon: 'none'
        });
      }
    },
    
    async onSearch(e) {
      try {
        console.log('[首页] 搜索:', e.detail.value);
        this.searchText = e.detail.value;
        this.page = 1;
        this.hasMore = true;
        this.articles = [];
        await this.loadArticles();
      } catch (error) {
        console.error('[首页] 搜索失败:', error);
      }
    },
    
    async loadMore() {
      if (this.hasMore && !this.loading) {
        console.log('[首页] 加载更多, 页码:', this.page + 1);
        this.page++;
        await this.loadArticles(true);
      }
    },
    
    async onRefresh() {
      console.log('[首页] 下拉刷新');
      this.isRefreshing = true;
      this.page = 1;
      this.hasMore = true;
      await this.loadArticles();
    },
    
    async refreshData() {
      // 静默刷新数据，不显示加载状态
      try {
        const categoryRes = await categoryApi.getList();
        if (categoryRes.code === 200) {
          this.categories = categoryRes.data.rows || [];
        }
        
        if (this.currentCategory) {
          await this.loadArticles();
        }
      } catch (error) {
        console.error('[首页] 静默刷新失败:', error);
      }
    },
    
    retry() {
      this.error = '';
      this.loadPageData();
    },
    
    goDetail(item) {
      console.log('[首页] 跳转详情:', item);
      uni.navigateTo({
        url: `/pages/detail/detail?id=${item.id}`,
        fail: (err) => {
          console.error('跳转详情失败:', err);
          uni.showToast({
            title: '打开详情失败',
            icon: 'none'
          });
        }
      });
    },
    
    getFirstImage(images) {
      if (!images) return '';
      try {
        // 空数组字符串直接返回空
        if (typeof images === 'string' && images.trim() === '[]') return '';
        let imageList = images;
        if (typeof images === 'string') {
          const cleanStr = images.replace(/\\/g, '');
          imageList = JSON.parse(cleanStr);
        }
        if (Array.isArray(imageList) && imageList.length > 0) {
          const firstImage = imageList[0];
          let imageUrl = '';
          if (typeof firstImage === 'object' && firstImage.url) {
            imageUrl = firstImage.url;
          } else if (typeof firstImage === 'string') {
            imageUrl = firstImage;
          }
          if (imageUrl) {
            if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
              return imageUrl;
            }
            return `${config.baseUrl}${imageUrl}`;
          }
        }
        return '';
      } catch (error) {
        console.error("解析图片失败:", error);
        return '';
      }
    },
    
    getTagArray(tags) {
      if (!tags) return [];
      if (typeof tags === 'string') {
        return tags.split(',').filter(tag => tag.trim() !== '');
      }
      return [];
    },
    
    onImageError(e) {
      console.error('[首页] 图片加载失败:', e);
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  padding: 10px 15px;
  border-bottom: 1px solid #eee;
}

.search-box {
  .search-input {
    display: flex;
    align-items: center;
    background-color: #f5f5f5;
    border-radius: 16px;
    padding: 8px 12px;
    
    .search-icon {
      font-size: 16px;
      margin-right: 8px;
      color: #999;
    }
    
    input {
      flex: 1;
      font-size: 14px;
    }
  }
}

.category-scroll {
  background-color: #fff;
  white-space: nowrap;
  border-bottom: 1px solid #eee;
  
  .category-list {
    display: inline-flex;
    padding: 0 15px;
  }
  
  .category-item {
    padding: 12px 16px;
    font-size: 14px;
    color: #666;
    position: relative;
    
    &-active {
      color: #333;
      font-weight: 500;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 20px;
        height: 2px;
        background-color: #333;
        border-radius: 1px;
      }
    }
  }
}

.content-scroll {
  flex: 1;
  margin-top: 10px;
}

.article-list {
  padding: 8px;
  
  .article-item {
    background: #fff;
    border-radius: 8px;
    margin-bottom: 12px;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0,0,0,0.05);
    
    .article-image {
      width: 100%;
      height: 200px;
    }
    
    .article-info {
      padding: 12px;
      
      .article-title {
        font-size: 16px;
        color: #333;
        font-weight: 500;
        line-height: 1.4;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .article-tags {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 8px;
        
        .tag {
          background: #f2f2f2;
          color: #666;
          font-size: 12px;
          padding: 2px 8px;
          border-radius: 12px;
          margin-right: 6px;
          margin-bottom: 6px;
        }
      }
      
      .article-desc {
        font-size: 14px;
        color: #666;
        line-height: 1.4;
        margin-bottom: 8px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .article-meta {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        font-size: 12px;
        color: #999;
        
        .meta-item {
          margin-right: 10px;
        }
      }
    }
  }
}

.loading, .no-more, .empty-state {
  padding: 16px 0;
  text-align: center;
}

.loading-text, .no-more-text, .empty-text {
  font-size: 14px;
  color: #999;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  padding: 20px;
}

.error-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  text-align: center;
}

.retry-btn {
  padding: 12px 24px;
  background-color: #007aff;
  color: #fff;
  border-radius: 6px;
  font-size: 16px;
}
</style>